<template>
    <div class="workorder">
        <div class="page-radio">
            <div class="radio-head">
                <el-radio v-model="workShop" :label="1" :disabled="globalState">机加工</el-radio>
                <el-radio v-model="workShop" :label="2" :disabled="globalState">走心机</el-radio>
            </div>
            <div class="radio-content" v-show="workShop === 1">
                <span class="content-tip">工序:</span>
                <div class="content-process">
                    <el-radio-group v-model="workShopProcess" :disabled="globalState">
                        <el-radio :label="2">热处理</el-radio>
                        <el-radio :label="3">车床</el-radio>
                        <el-radio :label="4">铣床</el-radio>
                        <el-radio :label="7">倒角</el-radio>
                        <el-radio :label="5">清洗机</el-radio>
                    </el-radio-group>
                </div>
            </div>
        </div>
        <div class="page-main">
            <div class="main-left">
                <el-form :model="formData" ref="leftForm" :rules="formDataRules" label-width="110px" label-position="left" size="mini" :hide-required-asterisk="false" :disabled="globalState"  class="demo-ruleForm">
                    <el-form-item label="设备" prop="equipment" class="form-item">
                        <el-select v-model="formData.equipment" remote filterable :remote-method="findEquipmentByDeviceCode" clearable placeholder="下拉选择设备" size="small">
                            <el-option v-for="(item,index) in formData.equipmentList" :label="item.deviceCode" :value="item.deviceCode" :key="index"></el-option>
                        </el-select>
                        <icon-svg name="sweep" width="25px" height="25px" color="" style="cursor:pointer;margin-left:1vw;" @click.native="sweep_btn('equipment')"></icon-svg>
                    </el-form-item>
                    <el-form-item label="品名" prop="materialCode">
                        <el-select v-model="formData.materialCode" filterable clearable placeholder="下拉选择产品" size="small">
                            <el-option v-for="(item,index) in formData.materialList" :label="item.materialCode" :value="item.materialCode" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="订单" prop="productOrder">
                        <el-select v-model="formData.productOrder" placeholder="下拉选择订单" size="small">
                            <el-option v-for="item,index in productOrderList" :label="item.productOrderNumber" :value="item.productOrderNumber" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="完成数量" prop="finishedNum">
                        <el-input v-model="formData.finishedNum" @input="dealQuantityEvent('finishedNum')" size="small" placeholder="请输入完成数量"></el-input>
                    </el-form-item>
                    <el-form-item label="不合格数" prop="unQualifiedNum" size="small">
                        <el-input :value="formData.unQualifiedNum" size="small" placeholder="自动计算" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="合格数量" size="small">
                        <el-input :value="formData.qualifiedNum"  placeholder="自动计算" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="计划数量" size="small">
                        <el-input :value="formData.planNumber" placeholder="自动读取" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="报工日期" prop="datetime" size="small">
                        <el-date-picker v-model="formData.datetime" :editable="false" type="date" size="small" :append-to-body="false" placeholder="选择日期时间" class="el-date-picker"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="作业员" size="small">
                        <el-input :value="userInfo.username" placeholder="自动读取当前用户" :disabled="true"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="main-right">
                <el-form :model="formData" ref="rightForm" :rules="formDataRules" label-width="110px" label-position="left" size="mini" :hide-required-asterisk="false" :disabled="globalState" class="demo-ruleForm">
                    <el-form-item label="工废数量" prop="scrapField1" size="small">
                        <el-input v-model.number="formData.scrapField1" @input="dealQuantityEvent('scrapField1')" size="small" placeholder="请输入工废数量"></el-input>
                    </el-form-item>
                    <el-form-item label="料废数量" prop="scrapField2" size="small">
                        <el-input v-model.number="formData.scrapField2" @input="dealQuantityEvent('scrapField2')" size="small" placeholder="请输入料废数量"></el-input>
                    </el-form-item>
                    <el-form-item v-if="formData.scrapField2 > 0" label="供应商" prop="supplierCode">
                        <el-select v-model="formData.supplierCode" filterable remote :remote-method="(query) => supplierRemoteMethod('search',query)" :loading="supplierRemoteLoading" @change="supplierChangeEvent" placeholder="下拉选择供应商" size="small">
                            <el-option v-for="item,index in supplierList" :label="item.name" :value="item.code" :key="index">
                                <span style="float: left">{{ item.code }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="刀废数量" prop="scrapQuantity" size="small">
                        <el-input v-model.number="formData.scrapQuantity" @input="dealQuantityEvent('scrapQuantity')" size="small" placeholder="请输入刀废数量"></el-input>
                    </el-form-item>
                    <el-form-item label="班次" prop="workshop">
                        <el-select v-model="formData.workshop" placeholder="下拉选择班次" size="small">
                            <el-option v-for="item,index in formData.classesList" :label="item.shiftType" :value="item.shiftType" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="出勤工时" prop="attendanceHours" size="small">
                        <el-input v-model="formData.attendanceHours" @input="formData.attendanceHours = String(formData.attendanceHours).replace(/[^0-9.]|(\.\d{2,})|\D(?=\.)|^\./g, '')" placeholder="请输入出勤工时"></el-input>
                    </el-form-item>
                    <el-form-item label="设备运行时长" prop="equipmentRunningHours" size="small">
                        <el-input v-model="formData.equipmentRunningHours" @input="validateInput('equipmentRunningHours')" placeholder="请输入设备运行时长(H)"></el-input>
                    </el-form-item>
                    <el-form-item label="停机信息">
                        <el-form size="mini">
                            <el-form-item>
                                <el-button plain type="primary"  @click="wirteDowntReason">{{ globalState ? "点击查看" : downtReasonBtnInfo }}</el-button>
                                <downt-reason :disabled="true" ref="downtReason" :downtReasonDisabled="globalState" :reasonDataList="formData.downtReasonList" @close="downtReasonClose"></downt-reason>
                            </el-form-item>
                        </el-form>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
  
<script>
import { reqUserInfo, reqProductOrderOfDay, reqProductOrderList, getDeviceAPI,reqDeviceInfo, reqSaveData, reqClassesList, reqMaterialInfoAndProductInfoByGid, reqWareHouseInfo, reqOrderResidueCount, reqSupplierList } from "@/api/workOrder.js";
import { qrCode } from "@/utils/jingzhi.js";
import DowntReason from "@/components/downtReason/index.vue";
export default {
    name:"workorder2",
    props:['tempData','state'],
    components:{
        DowntReason
    },
    data() {
        var validate1 = (rule, value, callback) => {
            let unQualifiedNum = this.formData.unQualifiedNum;
            const planNumber = this.formData.planNumber;
            if (value === '') {
                callback(new Error('请输入合格数量'));
            } else if (parseInt(value < 0)) {
                callback(new Error('输入的数量非法'));
            } else if (parseInt(value) > parseInt(planNumber)) {
                callback(new Error('输入的完成数量不能大于计划数量'));
            } else if(parseInt(unQualifiedNum) !== '' && parseInt(value) < parseInt(unQualifiedNum)){
                callback(new Error('完成数量不能小于不合格数量'));
            } else {
                callback();
            }
        };
        var validate2 = (rule, value, callback) => {
            let finishedNum =  this.formData.finishedNum;
            if (value === '') {
                callback(new Error('不合格数量为空'));
            } else if (parseInt(value < 0)) {
                callback(new Error('不合格数量非法'));
            } else if(parseInt(finishedNum) !== '' && parseInt(value) > parseInt(finishedNum)){
                callback(new Error('不合格数量不能大于完成数量'));
            } else {
                callback();
            }
        };
        const validatorSupplier = (rule,value,callback) => {
            const { scrapField2 } = this.formData;
            if(scrapField2 && String(value).length === 0){
                callback(new Error('请选择供应商'));
            } else {
                callback();
            }
        };
        return {
            userInfo:{
                username:"",
                userId:"",
                userPhone:""
            },
            workShop:"",  //车间类型 机加工|走心机
            workShopProcess:"",
            formData:{
                materialCode:"",  //品名/物料编号
                materialName:"",
                materialList:[],  //品名下拉数组
                productOrder:"",  //订单号
                productOrderList:[],  //订单列表
                equipment:"",  //选择设备编码
                equipmentName:"",
                gid:"",  //设备所在车间id
                equipmentList:[],
                finishedNum:'',  //完成数量
                unQualifiedNum:'',  //不合格数量
                materialAndProductInfoList:[],
                planNumber:"",  //计划数量
                workshop:"",  //班次
                classesList:[],
                qualifiedNum:"",
                downtReasonList:[],
                datetime:new Date(),  //报工时间
                attendanceHours:null,
                equipmentRunningHours:"",
                scrapField1:0, //工废
                scrapField2:0,
                scrapField1Reason:'',
                scrapField2Reason:'',
                supplierName:'',
                supplierCode:'',
                scrapQuantity:''
            },
            formDataRules:{
                materialCode:[{required:true, message:"请选择产品", trigger: 'change'}],
                productOrder:[{required:true, message:"请选择订单号", trigger: 'change'}],
                equipment:[{required:true, message:"请选择设备", trigger: 'change'}],
                finishedNum: [{required:true, validator: validate1, trigger: 'blur' }],  //完成数量
                unQualifiedNum:[{required:false, validator: validate2, trigger: 'blur' }],  //不合格数量
                workshop:[{required:true, message:"请选择班次", trigger: 'change'}],
                datetime: [{ required: true, message: '请选择报工时间', trigger: 'blur'}],
                attendanceHours: [{ required: true, message: '出勤工时不能为空', trigger: 'blur'}],
                equipmentRunningHours:[{ required: false, message: '设备运行时长不能为空', trigger: 'blur'}],
                scrapField1: [{required:true, message:'请填写工废数量', trigger: 'blur'}],
                scrapField2: [{required:true, message:'请填写料废数量', trigger: 'blur'}],
                supplierCode: [{required:true, validator:validatorSupplier, trigger: 'blur'}],
                scrapQuantity: [{required:true, message:'请填写刀废数量', trigger: 'blur'}],
            },
            equipmentFirstChange:true,
            materialCodeFirstChange:true,
            productOrderFirstChange:true,
            workShopFirstChange:true,
            //机加工 工废 料废
            jjg_waste_gf:['换型','换刀','崩刀','断刀','过切','装夹不良','落地件','工废','大小边','其它'],
            jjg_waste_lf:[],
            //走心机 工废 料废
            zxj_waste_gf:['换刀','换型','冷热机','尺寸','铁屑划伤','崩刀','来料不良','工程打样','其它'],
            zxj_waste_lf:['来料表面伤','材料开裂','棒料弯曲','棒料大小不合格','其它'],
            //装配车间 工废 料废
            zp_waste_gf:['打码','压装','焊接','铆接','调机','返修','外协','其它'],
            zp_waste_lf:['大小边','砂眼','外协','未光到','裂纹','卡滞','尺寸','其它'],
            supplierRemoteLoading:false,
            supplierList:[]
        };
    },
    mounted(){
        console.log('获取到父组件传递过来的数据',this.tempData,this.state);
        if(this.tempData.workShopCode == 1 || this.tempData.workShopCode == 2){
            this.formData.materialCode = this.tempData.productCode;
            this.formData.materialName = this.tempData.productName;
            this.formData.productOrder = this.tempData.productNumber;
            this.formData.equipment = this.tempData.machineCode;
            this.formData.equipmentName = this.tempData.machine;
            this.formData.finishedNum = this.tempData.completedQuantity;
            this.formData.unQualifiedNum = this.tempData.unqualifiedQuantity;
            this.formData.planNumber = this.tempData.plannedQuantity;
            this.formData.workshop = this.tempData.classes;
            this.formData.qualifiedNum = this.tempData.qualifiedQuantity;
            this.formData.datetime = this.tempData.reportDate;
            this.formData.attendanceHours = this.tempData.attendanceHours;
            this.formData.downtReasonList = this.tempData.downtimeReportlList;
            this.formData.equipmentRunningHours = this.tempData.operatingTime;
            this.userInfo.username = this.tempData.operator;
            this.userInfo.userId = this.tempData.operatorId;
            this.userInfo.userPhone = this.tempData.operatorPhone;
            this.workShop = parseInt(this.tempData.workShopCode);
            this.workShopProcess = this.tempData.workReportCode || '';
            this.formData.scrapField1 = this.tempData.laborCostQuantity || 0;
            this.formData.scrapField2 = this.tempData.materialScrapQuantity || 0;
            this.formData.scrapField1Reason = this.tempData.workScrapReason || '';
            this.formData.scrapField2Reason = this.tempData.materialScrapReason || '';
            this.formData.supplierName = this.tempData.supplierName || '';
            this.formData.supplierCode = this.tempData.supplierCode || '';
            this.formData.scrapQuantity = this.tempData.materialScrapQuantity || '';
            if(this.formData.scrapField2 > 0){
                this.supplierList = [{ name:this.formData.supplierName,code:this.formData.supplierCode }]
            }
        }
        if(this.state === 0){
            //审核状态
        } else if(this.state === 1){
            //编辑状态
            this.getDeviceList();
            this.getClassList();
        }
    },
    computed:{
        globalState(){
            let state = this.state;
            if(state === 0 || state === 2){
                return true;
            }
            if(state === 1){
                return false;
            }
            return false;
        },
        //订单列表信息
        productOrderList(){
            let code = this.formData.materialCode;
            let list = this.formData.materialAndProductInfoList;
            return list.filter(v => v.materialCode === code).map(k => {
                return {productOrderNumber:k.productOrderNumber,planQuantity:k.planQuantity, unqualifiedCount:k.unqualifiedCount};
            })
        },
        downtReasonBtnInfo(){
            const downtReasonList = this.formData.downtReasonList;
            let tip = "点击填写";
            if(downtReasonList.length > 0){
                for(let i = 0; i < downtReasonList.length; i ++){
                    if(Number(downtReasonList[i].downtimeDuration) > 0){
                        tip = "点击修改";
                        return tip;
                    }
                }
                return tip;
            } else {
                return tip;
            }
        },
        wasteList_gf(){
            const workShop = this.workShop;
            if(workShop == 1){
                return this.jjg_waste_gf;
            } else if(workShop == 2){
                return this.zxj_waste_gf;
            } else {
                return [];
            }
        },
        wasteList_lf(){
            const workShop = this.workShop;
            if(workShop == 1){
                return this.jjg_waste_lf;
            } else if(workShop == 2){
                return this.zxj_waste_lf;
            } else {
                return [];
            }
        }
    },
    watch:{
        //监听物料选择的变化
        "formData.materialCode":{
            handler(newVal, oldVal){
                if(this.materialCodeFirstChange){
                    this.materialCodeFirstChange = false;
                    return;
                }
                if(newVal !== oldVal && newVal !== ""){
                    this.formData.productOrder = "";
                    let arr = this.formData.materialList.filter(item => item.materialCode === this.formData.materialCode);
                    if(arr.length > 0){
                        this.formData.materialName = arr[0].materialName;
                    }
                }
                if(newVal === ""){
                    this.formData.materialName = "";
                    this.formData.productOrder = "";
                }
            }
        },
        //监听订单的选择
        "formData.productOrder":{
            handler(newVal, oldVal){
                if(this.productOrderFirstChange){
                    this.productOrderFirstChange = false;
                    return;
                }
                if(newVal !== oldVal && newVal !== ""){
                    let orderInfo = this.productOrderList.filter(item => item.productOrderNumber === this.formData.productOrder)[0];
                    this.formData.planNumber = orderInfo.planQuantity;
                }
                if(newVal === ""){
                    this.formData.planNumber = "";
                    this.formData.finishedNum = "";
                    this.formData.unQualifiedNum = "";
                }
            }
        },
        //监听设备的选择
        "formData.equipment":{
            handler(newVal, oldVal){
                if(this.equipmentFirstChange){
                    this.equipmentFirstChange = false;
                    return;
                }
                if(newVal !== "" && newVal !== oldVal){
                    let arr = this.formData.equipmentList.filter(item => item.deviceCode === this.formData.equipment);
                    if(arr.length > 0){
                        this.formData.gid = arr[0].gid;
                        this.formData.equipmentName = arr[0].deviceName;
                    }
                    //更新物料列表信息
                    this.getMaterialInfoAndProductInfo();
                    //清空数据
                    this.formData.productOrder = "";
                    this.formData.planNumber = "";
                    this.formData.materialCode = "";
                }
                if(newVal === ""){
                    this.getDeviceList();
                    this.formData.materialCode = "";
                    this.formData.productOrder = "";
                    this.formData.materialList = [];
                    this.formData.productOrderList = [];
                }
            }
        },
        //监听车间 机加工/走心机的选择
        workShop:{
            handler(newVal,oldVal){
                if(this.workShopFirstChange){
                    this.workShopFirstChange = false;
                    return;
                }
                this.formData.equipment = "";
                this.getDeviceList();
            }
        }
    },
    methods: {
        //获取当前用户信息
        async getUserInfo () {
            reqUserInfo().then(res => {
                if(res.data.code === 200){
                    this.userInfo.username = res.data.data.nickname;
                    this.userInfo.userId = res.data.data.id;
                    this.userInfo.userPhone = res.data.data.mobile;
                }
                console.log("获取当前用户信息",res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //选择号物料后查询订单信息
        async getProductOrderList () {
            let materialCode = "";
            if(this.formData.materialList.length === 0){
                materialCode = this.tempData.productCode;
            } else {
                materialCode = this.formData.materialList.filter(item => item.code === this.formData.materialName)[0].code;
            }
            if(materialCode === "") return ;
            reqProductOrderList(materialCode).then(res => {
                if(res.data.code === 200){
                    this.formData.productOrderList = res.data.data.content;
                }
                console.log("通过物料编码/品名查询订单信息",res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //获取设备列表信息
        async getDeviceList () {
            let workshop = this.workShop === 1 ? 143533 : 143532;
            getDeviceAPI(workshop).then(res => {
                if(res.data.code === 200){
                    this.formData.equipmentList = res.data.data.map(item => {
                        return {deviceId:item.deviceId, deviceCode:item.deviceCode, deviceName:item.deviceName, gid:item.gid, gname:item.gname};
                    });

                    //编辑页面一打开 需要查询物料和订单信息 但此时设备列表还未获取到
                    let arr = this.formData.equipmentList.filter(item => item.deviceCode === this.formData.equipment);
                    if(arr.length > 0){
                        this.formData.gid = arr[0].gid;
                        this.getMaterialInfoAndProductInfo();
                    }
                }
                console.log('获取设备列表信息',res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //获取班次信息
        async getClassList() {
            reqClassesList().then(res => {
                if(res.data.code === 200){
                    this.formData.classesList = res.data.data;
                }
                console.log('获取班次信息',res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        //查询当前选择设备所在车间的订单及物料信息
        async getMaterialInfoAndProductInfo () {
            let gid = this.formData.gid;
            console.log("设备所在车间:",gid);
            if(!gid){
                this.formData.materialList = [];
                this.formData.productOrderList = [];
                return;
            }
            reqMaterialInfoAndProductInfoByGid(gid).then(response => {
                if(response.status === 200){
                    this.formData.materialAndProductInfoList = response.data;

                    let temp  = response.data.map(item => {
                        return {materialCode:item.materialCode,materialName:item.materialName};
                    });
                    this.formData.materialList = temp.filter((item,index,self) => {
                        return self.findIndex(t => t.materialCode === item.materialCode) === index;
                    })
                    console.log('获取设备所在车间品名数据',temp,this.formData.materialList);
                }
                console.log('通过设备所在车间获取订单和物料信息',response);
            }).catch(err => {
                this.$message({type:"error",message:err})
            })
        },
        //保存、取消按钮
        async save_btn(){
            let workShop = this.workShop;
            let workShopProcess = workShop === 1 ? this.workShopProcess : '';
            if(workShop === "") return this.$message({type:"info",message:"请选择车间类型!"});
            if(workShop === 1 && workShopProcess === "") return this.$message({type:"info",message:"请选择工序!"});
            let workShopProcessName = "";
            switch (workShopProcess) {
                case 2:
                    workShopProcessName = "热处理";
                    break;
                case 3:
                    workShopProcessName = "车床";
                    break;
                case 4:
                    workShopProcessName = "铣床";
                    break;
                case 5:
                    workShopProcessName = "清洗机";
                    break;
                case 7:
                    workShopProcessName = "倒角";
                    break;
                default:
                    break;
            }
            let validateResult1 = false;
            let validateResult2 = false;
            this.$refs.leftForm.validate((valid) => {
                if (valid) {
                    validateResult1 = true;
                } else {
                    validateResult1 = false;
                    return false;
                }
            });
            this.$refs.rightForm.validate((valid) => {
                if (valid) {
                    validateResult2 = true;
                } else {
                    validateResult2 = false;
                    return false;
                }
            });
            if(!(validateResult1 && validateResult2)) return ;
            //准备参数
            const { materialName, materialCode, productOrder, equipment, equipmentName, finishedNum, unQualifiedNum, planNumber, workshop, datetime, attendanceHours, downtReasonList,equipmentRunningHours } = this.formData;
            //保存前判断报工前的完成数量是否合理
            try {
                const result = await reqOrderResidueCount({productNumber:productOrder,workReportCode:workShopProcess,plannedQuantity:planNumber});
                if(result.data || result.data.code === 200){
                    const value = result.data.data;
                    if(Number(finishedNum) > Number(value)){
                        this.$alert(`完成数量不能大于当前订单已报工完剩余的计划数量(${value})`,'提示',{confirmButtonText:"确定",callback:action => {}});
                        return;
                    }
                }
                console.log('获取当前订单剩余计划数api',result);
            } catch (error) {
                this.$message({type:"error",message:"请求订单剩余计划数量出错,请重试"});
                console.log('获取当前订单剩余计划数api',error);
                return ;
            }
             const { scrapField1,scrapField1Reason,scrapField2,scrapField2Reason,scrapQuantity,supplierCode,supplierName } = this.formData;
            let paramsObj = {
                id:this.tempData.id,
                productCode:materialCode,
                productName:materialName,
                workReportType:workShopProcessName,
                workReportCode:workShopProcess,
                productNumber:productOrder,
                plannedQuantity:planNumber,
                completedQuantity:finishedNum,
                qualifiedQuantity: finishedNum - unQualifiedNum,
                unqualifiedQuantity:unQualifiedNum,
                attendanceHours:attendanceHours,
                reportDate:this.formatDate(datetime,1),
                operatorId:this.userInfo.userId,
                operator:this.userInfo.username,
                operatorPhone:this.userInfo.userPhone,
                username:this.tempData.username,
                reviewStatus:0,
                classes:workshop,
                classesTime:this.formData.classesList.filter(item => item.shiftType === workshop)[0].workTime,
                machine:equipmentName,
                machineCode:equipment,
                workShop:workShop === 1 ? '机加工' : '走心机',
                workShopCode:workShop,
                productionProcessList:[],
                processMaterialList:[],
                appealStatus:0,
                appealRemark:"",
                inspectionPerson:"",
                inspectionPersonCode:"",
                warehouseCode:"",
                warehouseId:"",
                teamName:this.tempData.teamName,
                downtimeReportlList:downtReasonList,
                operatingTime:equipmentRunningHours,
                laborCostQuantity:scrapField1,
                workScrapReason:'',
                materialScrapQuantity:scrapField2,
                materialScrapReason:'',
                toolCostQuantity:scrapQuantity,supplierCode,supplierName
            }
            //判断是申诉状态下的编辑弹出提示
            if(this.tempData.appealStatus == 1){
                this.$confirm('该工单是申诉工单, 确认已修改其申诉内容后再进行保存!', '提示', { confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'})
                .then(() => {
                    //
                    reqSaveData(paramsObj).then(res => {
                        console.log("保存数据api",res);
                        if(res.data.code === 200){
                            this.$emit("message",true);
                            return;
                        }
                        this.$emit("message",false);
                    }).catch(err => {
                        this.$emit("message",false);
                    })
                }).catch(() => {
                    this.$message({type: 'info',message: '已取消!'});       
                });
                return;
            }

            reqSaveData(paramsObj).then(res => {
                console.log("保存数据api",res);
                if(res.data.code === 200){
                    this.$emit("message",true);
                    return;
                }
                this.$emit("message",false);
            }).catch(err => {
                this.$emit("message",false);
            })
        },
        //格式化时间
        formatDate(val,type){
            let date = new Date(val);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            if(type === 0){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 1){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day);
            } else if (type === 2){
                return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            } else if (type === 3){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
            }
        },
        addZero(val){
            return val > 9 ? val : "0" + val;
        },
        //点击扫码
        async sweep_btn(type){
            if(this.globalState){
                return;
            }
            try {
                let res = await qrCode();
                switch (type) {
                    case 'equipment':
                        this.formData.equipment = res;
                        this.findEquipmentByDeviceCode(res);
                        break;
                    default:
                        break;
                }
                console.log('调用精致提供的扫码api',res);
            } catch (error) {
                this.$message({type:"warning",message:error});
            }
        },
        //物料搜索
        remoteMethod(materialCode){
            if(materialCode.trim() === "") {
                this.getMaterialInfoAndProductInfo();
                return;
            }
            reqMaterialsInfo(materialCode).then(response => {
                if(response.data.code === 200 && response.data.data !== null){
                    let { code, id, name } = response.data.data.materialFields;
                    this.formData.materialList = [{code,id,name}];
                }
                if(response.data.code === 200 && response.data.data === null){
                    this.formData.materialList = [];
                }
                console.log('根据物料编号查询物料',response);
            }).catch(error => {
                this.$message({type:"error",message:error});
            })
        },
        //查找设备
        findEquipmentByDeviceCode (val) {
            if(val.trim() === "") return;
            reqDeviceInfo(val).then(res => {
                if(res.data.code === 200){
                    this.formData.equipmentList = res.data.data.content.map(item => {
                        return {deviceId:item.deviceId, deviceCode:item.deviceCode, deviceName:item.deviceName, gid:item.gid, gname:item.gname};
                    });
                }
                console.log('获取设备信息,通过设备编号',res);
            }).catch(err => {
                this.$message({type:"error",message:err});
            })
        },
        wirteDowntReason(){
            this.$refs.downtReason.dialogFormVisible = true;
        },
        downtReasonClose(parameter){
            this.formData.downtReasonList = parameter;
        },
        validateInput(bindDataName) {
            const inputValue = this.formData[bindDataName];
            const regex = /^\d+(\.\d{0,1})?$/;
            if (!regex.test(inputValue) && inputValue !== '') {
                this.formData[bindDataName] = inputValue.slice(0, -1);
            }
        },
        dealQuantityEvent(field){
            this.formData[field] = String(this.formData[field]).replace(/[^\d]/g, '');
            const { finishedNum,scrapField1,scrapField2,scrapQuantity } = this.formData;
            this.formData.unQualifiedNum = Number(scrapField1) + Number(scrapField2) + Number(scrapQuantity);
            this.formData.qualifiedNum = (Number(finishedNum) - this.formData.unQualifiedNum) >= 0 ? Number(finishedNum) - this.formData.unQualifiedNum : 0;
        },
        supplierChangeEvent(supplierCode){
            const supp = this.supplierList.find(item => item.code === supplierCode);
            if(supp) this.formData.supplierName = supp.name;
        },
        supplierRemoteMethod(type = 'init',query){
            if(type == 'init' || query == ''){
                this.supplierRemoteLoading = true;
                reqSupplierList().then(response => {
                    const list = response.data.data.content;
                    this.supplierList = list.map(item => ({ code: item.code, name: item.name }));
                    this.supplierRemoteLoading = false;
                },error => {
                    this.supplierRemoteLoading = false;
                    this.supplierList = [];
                })
            }
            if (query !== '' && type == 'search') {
                this.supplierRemoteLoading = true;
                reqSupplierList({ code:query,name:query }).then(response => {
                    const list = response.data.data.content;
                    this.supplierList = list.map(item => ({ code: item.code, name: item.name }));
                    this.supplierRemoteLoading = false;
                },error => {
                    this.supplierRemoteLoading = false;
                    this.supplierList = [];
                })
            } else {
                this.supplierList = [];
            }
        }
    },
}
</script>
  
<style lang="scss" scoped>
  .workorder{
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
    user-select: none;
    .page-main{
        width: 100%;
        display: flex;
        justify-content: space-around;
        .main-left{
            width: 45%;
            box-sizing: border-box;
        }
        .main-right{
            width: 45%;
            box-sizing: border-box;
        }
    }
    .page-radio{
        width: 95%;
        margin: 10px 0;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        .radio-content{
            margin: 10px 0;
            display: flex;
            align-items: center;
            .content-tip{
                margin-right: 15px;
                font-size: 14px;
            }
        }
    }
  }
  //表单项
  ::v-deep .form-item{
    width: 95%;
    .el-form-item__content{
        display: flex;
        align-items: center;
    }
  }
  .el-date-picker{
    width: 70%;
  }
</style>
  